package cn.sinata.xldutils_kotlin.utils

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import cn.sinata.xldutils_kotlin.R
import java.util.ArrayList

/**
 * 权限相关处理
 */
val Activity.SETTING_REQUEST_CODE: Int
    get() = 101

fun Fragment.permission(permission:String, dialogMessage:String, requestCode:Int) = activity.permission(permission, dialogMessage, requestCode)
fun Fragment.permission(permission: Array<String>, dialogMessage: String, requestCode: Int) = activity.permission(permission, dialogMessage, requestCode)

fun Activity.permission(permission:String, dialogMessage:String, requestCode:Int):Boolean =
        permission(arrayOf(permission),dialogMessage,requestCode)

fun Activity.permission(permission: Array<String>, dialogMessage: String, requestCode: Int): Boolean {
    val permissionList = ArrayList<String>()
    val permissionNoNotice = ArrayList<String>()
    if (permission.isNotEmpty()) {
        for (s in permission) {
            if (ContextCompat.checkSelfPermission(this, s) != PackageManager.PERMISSION_GRANTED) {
                //是否是第一次请求该权限
                val isFirst = SPUtils.instance().getBoolean(s, true)
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, s) && !isFirst) {
                    permissionNoNotice.add(s)
                } else {
                    permissionList.add(s)
                }
            }
        }
        if (permissionList.size > 0 || permissionNoNotice.size > 0) {
            if (permissionNoNotice.size > 0) {
                val title = String.format("请授予%s应用%s权限,否则无法正常工作！请于\"设置\"－\"应用\"-\"权限\"中配置权限。", this.resources.getString(R.string.app_name), dialogMessage)
                this.alertDialog(dialogMessage, title, false, "去设置", "取消", DialogInterface.OnClickListener { _, _ ->
                    val intent = Intent(
                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                    intent.data = Uri.parse("package:" + this.packageName)
                    this.startActivityForResult(intent, this.SETTING_REQUEST_CODE)
                }, DialogInterface.OnClickListener { _, _ -> this.finish() })
            }
            if (permissionList.size > 0)
                ActivityCompat.requestPermissions(this, permissionList.toTypedArray(),
                        requestCode)
            return false
        } else {
            return true
        }
    } else {
        return true
    }
}